package net.lzzy.controller;

import net.lzzy.entity.Article;
import net.lzzy.entity.Comment;
import net.lzzy.repository.ArticleRepository;
import net.lzzy.service.ArticleService;
import net.lzzy.service.CommentService;
import net.lzzy.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class ClientController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private RoleService roleService;

    //访问主页时转到分页的第一页
    @GetMapping("/")
    public String index(Model model) {
        return page(1, model);
    }

    //分页显示文章
    @GetMapping("/page/{page}")
    public String page(@PathVariable("page") int page, Model model) {
        //分页每页文章数
        int size = 9;
        Page<Article> articles = articleService.pageArticle(page - 1, size);
        model.addAttribute("page", page);
        model.addAttribute("totalPage", articles.getTotalPages());
        model.addAttribute("articles", articles.getContent());
        return "client/index";
    }

    //文章详情页
    @GetMapping("/article/{id}")
    public String article(@PathVariable("id") int id, Model model) {
        Article article = articleService.findArticleById(id);
        List<Comment> comments = commentService.findCommentByArticleId(id);
        model.addAttribute("article", article);
        model.addAttribute("comments", comments);
        return "client/article";
    }

    //发表评论
    @PostMapping("/article/{id}/comment")
    public String comment(@PathVariable("id") int id, @RequestParam("author") String author, @RequestParam("content") String content) {
        commentService.addComment(id, author, content);
        return "redirect:/article/" + id;
    }




}
